﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Fluent;
//using VIBlend.WPF.Controls;
using System.Data;
using System.Globalization;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Threading;

namespace AnonsaiWPF
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;// = delegate { };

        #region Properties
        private string _amid;
        public string AnonsId
        {
            get { return _amid; }
            set
            {
                if (value != _amid)
                {
                    _amid = value;
                    OnPropertyChanged("AnonsId");
                }
            }
        }
        #endregion Properties

        protected void OnPropertyChanged(string name)
        {
            // AnnouncInsert anin = new AnnouncInsert();
            //anin.AnonsId=this.AnonsId;
            //this.DataContext = anin;
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
       // SplashScreen splash = new SplashScreen("Images/loading.gif");
        delegate void UpdateDGCallback(DataTable tb);
        delegate string GetHeaderCallback(DataGrid dg,int ix);
        private static Splasher splash=new Splasher();
        private BackgroundWorker worker = new BackgroundWorker();
        private BackgroundWorker worker1 = new BackgroundWorker();
        DataTable tbtinklelis;
        DataTable planasTable = null;
        DataTable autoplan;
        Random rd=new Random(100);
        public static string serachWord = "";
        public static string serachAnWord = "";
        public static string copyAnonsId = "-1";
        private static readonly Random getrandom = new Random();
        private static readonly object syncLock = new object();

        public static int GetRandomNumber(int min, int max)
        {
            lock (syncLock)
            { // synchronize
                return getrandom.Next(min, max);
            }
        }

        private DataTable recalcStartTime(DataTable tb)
        {
            TimeSpan zeroduration = new TimeSpan(0);
            TimeSpan sum = new TimeSpan(0);
            for (int i = 1; i < (tb.Rows.Count); i++)
            {
                string durat = tb.Rows[i-1]["Duration"].ToString();
                TimeSpan duration = new TimeSpan(0);
                TimeSpan.TryParse(durat, out duration);
                string time = tb.Rows[i-1]["StartTime"].ToString();
                TimeSpan starttime = new TimeSpan(0);
                TimeSpan.TryParse(time, out starttime);
                int blockpospre = Int32.Parse(tb.Rows[i-1]["BlockPos"].ToString());
                
                if (blockpospre > -1)
                {
                    tb.Rows[i]["StartTime"] = (starttime + duration).ToString();
                    sum = sum + duration;
                    
                }
                if (i < tb.Rows.Count-1)
                    if ((duration > zeroduration) && (tb.Rows[i]["Name"].ToString().Equals("")) && (!tb.Rows[i - 1]["Name"].ToString().Equals("")))
                {
                    tb.Rows[i]["Duration"] = sum.ToString();
                    tb.Rows[i]["BlkDuration"] = tb.Rows[i-1]["BlockDuration"];
                    sum = new TimeSpan(0);
                    TimeSpan dur;
                    TimeSpan.TryParse(tb.Rows[i]["Duration"].ToString(), out dur);
                    TimeSpan blkdur;
                    TimeSpan.TryParse(tb.Rows[i]["BlkDuration"].ToString(), out blkdur);
                    if (dur > blkdur)
                    {
                      
                       for (int y=i-1;y>0;y--){
                           string bid = tb.Rows[y - 1]["BlockPos"].ToString(); 
                           tb.Rows[y]["Color"] = "Red";
                           if (bid == "-1") break;
                       }
                       if (tb.Rows[1]["Color"] == "Red") tb.Rows[0]["Color"] = "Red";
                    }
                }
                
            }
            return tb;
        }

        private void UpdateDG(DataTable tb)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (gridDataTinklelis.Dispatcher.CheckAccess())
            {
               tb=recalcStartTime(tb);
               this.gridDataTinklelis.ItemsSource = tb.AsDataView();
            }
            else
            {
                UpdateDGCallback d = new UpdateDGCallback(UpdateDG);
                //this.Invoke();
                this.gridDataTinklelis.Dispatcher.Invoke(d, new object[] { tb });
            }
        }

        public string GetHeader(DataGrid dg, int ix)
        {
            string header = "";
            DataGridColumn textColumn = dg.Columns[ix];
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (dataGrid1.Dispatcher.CheckAccess())
            {
                //DataGridColumn textColumn = dg.Columns[ix];
                header=textColumn.Header.ToString();

            }
            else
            {
                GetHeaderCallback d = new GetHeaderCallback(GetHeader);
                header=(string)this.dataGrid1.Dispatcher.Invoke(d, new object[] { dg, ix });
            }
            //return textColumn.Header.ToString();
            return header;
        }

        private static DataBase GetDb()
        {
            DataBase db = new DataBase("192.168.100.100\\SQLEXPRESS", "sa", "tornado", "PASystem");
            return db;
        }

        public MainWindow()
        {
            InitializeComponent();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker1.DoWork += worker_DoWork1;
            worker1.RunWorkerCompleted += worker_RunWorkerCompleted1;

            DataBase db = GetDb();
            DataTable tb = db.getTable("select * from Anonsai an left join AnonsaiClips anc on an.ClipId=anc.id");
            gridControl1.View.ShowGroupPanel = false;

           // DataTable tb1 = db.getTable("select limit 100, * from Clips");
            //gridControl2.DataSource = tb1;
            gridControl2.View.ShowGroupPanel = false;

            blockGrid1.View.ShowGroupPanel = false;
            blockGrid2.View.ShowGroupPanel = false;
            blockGrid3.View.ShowGroupPanel = false;
            blockGrid4.View.ShowGroupPanel = false;
            blockGrid5.View.ShowGroupPanel = false;
            blockGrid6.View.ShowGroupPanel = false;
            blockGrid7.View.ShowGroupPanel = false;
            Functionality.getBlocks(blockGrid1, "Monday");
            Functionality.getBlocks(blockGrid2, "Tuesday");
            Functionality.getBlocks(blockGrid3, "Wednesday");
            Functionality.getBlocks(blockGrid4, "Thursday");
            Functionality.getBlocks(blockGrid5, "Friday");
            Functionality.getBlocks(blockGrid6, "Saturday");
            Functionality.getBlocks(blockGrid7, "Sunday");
            //string dw=DateTime.Now.DayOfWeek.ToString();

            //gridControlTinklelis.View.ShowGroupPanel = false;
            //pivotGridControl1.DataSource = tb;
            //gridControlTinklelisView.RowStyle += tinklelis_RowStyle;

            this.DataContext = this;
            TabAnonsai.IsEnabled = false;
            TabKlipai.IsEnabled = false;
            TabBlokai.IsEnabled = false;
            TabTinklelis.IsEnabled = false;
            TabPlanas.IsEnabled = false;
            TabAutoPlanas.IsEnabled=false;
            DataTable tbaccess = db.getTable("select Tabs from AccessRights where Computer='" + System.Environment.MachineName + "'");
            if (tbaccess.Rows.Count>0){
                string[] tabs=tbaccess.Rows[0][0].ToString().Split('|');
                for (int i = 0; i < tabs.Length; i++)
                {
                    for(int y=0;y<MainRibbon.Tabs.Count;y++){
                        if (MainRibbon.Tabs[y].Tag.Equals(tabs[i])){
                            MainRibbon.Tabs[y].IsEnabled=true;
                        }
                    }
                }
               
            }
           // gridTinklelis.Visibility = Visibility.Hidden;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string dt = (string)e.Argument;
            // run all background tasks here
            DataBase db = new DataBase("192.168.100.100\\SQLEXPRESS", "sa", "tornado", "PASystem");
            string dayofweek = DateTime.Parse(dt).DayOfWeek.ToString();
            string date = DateTime.Parse(dt).ToShortDateString();
            DataTable tbtinklelisInit = db.getTable("select * from AnonsData left join BlockAnons on (BlockPos=BlockNr ) left join Anonsai a  on AnonsId=a.Id left join  AnonsaiClips ac on ClipId=ac.Id  where AnonsDate='" + dt + "' and CHARINDEX((SELECT DATENAME(dw, CONVERT(datetime,'" + dt + "'))) , WeekDay) > 0 ");
            DataTable auto = db.getTable("select * from AutoPlan where dateTime='" + date + "'");
            DataTable blocks =null;
            if (Functionality.BlockByDateExists(date))
            {
                blocks = db.getTable("select * from BlockAnons where WeekDay='" + date + "' order by BlockNr");
            }
            else
            {
                blocks = db.getTable("select * from BlockAnons where WeekDay='" + dayofweek + "' order by BlockNr");
            }
            tbtinklelis = db.getTable("select * from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id left join BlockAnons ba on ad.BlockId=ba.Id where AnonsDate='1900-01-01'");
            if (!tbtinklelis.Columns.Contains("Color"))
                tbtinklelis.Columns.Add("Color", typeof(string));
            if (!tbtinklelis.Columns.Contains("BlkDuration"))
                tbtinklelis.Columns.Add("BlkDuration", typeof(string));

           // List<DataTable> genericlist = e.Argument as List<DataTable>;
           // DataTable blocks = genericlist[0];
          //  DataTable tbtinklelis1 = genericlist[1];
           // DataTable tbtinklelisTmp = genericlist[2];
           // gridDataTinklelis.ItemsSource = tbtinklelis.AsDataView();
            for (int i = 0; i < blocks.Rows.Count; i++)
            {
                DataRow rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                //string bpos = blocks.Rows[i][1].ToString().Replace("Blokas", "");
                rl["BlockPos"] = blocks.Rows[i]["BlockNr"].ToString();// Int32.Parse(bpos);
                rl["StartTime"] = blocks.Rows[i]["AnonsTime"].ToString();
                string bid = blocks.Rows[i]["BlockNr"].ToString().Replace("Blokas", "");
                rl["BlockId"] = blocks.Rows[i]["BlockNr"].ToString();// Int32.Parse(bid);
                rl["AnonsId"] = "1";
                rl["Duration"]=Functionality.getDurationByAnonsId("1");
                rl["Name"] = Functionality.getNameByAnonsId("1");
                rl["ProgName"] = blocks.Rows[i]["ProgName"].ToString();
                rl["BlockDuration"] =blocks.Rows[i]["BlockDuration"];
                rl["Color"] = "Yellow";
                tbtinklelis.Rows.Add(rl);
                //DataTable tbtinklelisTmp = db.getTable("select * from AnonsData where AnonsDate='" + dt + "' and BlockId=" + bid);
                DataTable tbtinklelisTmp = db.getTable("select * from AnonsData left join BlockAnons on (BlockPos=BlockNr ) left join Anonsai a  on AnonsId=a.Id left join  AnonsaiClips ac on ClipId=ac.Id  where AnonsDate='" + dt + "' and CHARINDEX((SELECT DATENAME(dw, CONVERT(datetime,'" + dt + "'))) , WeekDay) > 0 and BlockId=" + bid);
                for (int y = 0; y < tbtinklelisTmp.Rows.Count; y++)
                {
                    rl = tbtinklelis.NewRow();
                    rl["Id"] = "1";
                    rl["BlockPos"] = tbtinklelisTmp.Rows[y]["BlockPos"].ToString();
                    rl["StartTime"] = tbtinklelisTmp.Rows[y]["AnonsTime"].ToString();
                    rl["Duration"] = tbtinklelisTmp.Rows[y]["Duration"].ToString();
                    rl["BlockId"] = tbtinklelisTmp.Rows[y]["BlockId"].ToString();
                    rl["AnonsId"] = tbtinklelisTmp.Rows[y]["AnonsId"].ToString();
                    rl["Name"] = tbtinklelisTmp.Rows[y]["Name"].ToString();
                    rl["ProgName"] = blocks.Rows[i]["ProgName"].ToString();
                    rl["BlockDuration"] = blocks.Rows[i]["BlockDuration"];
                    rl["Color"] = "Grey";
                    tbtinklelis.Rows.Add(rl);
                }
                rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = blocks.Rows[i]["BlockNr"].ToString(); ;
                rl["AnonsId"] = "1";
                rl["Duration"] = Functionality.getDurationByAnonsId("1");
                rl["Name"] = Functionality.getNameByAnonsId("1");
                rl["ProgName"] = blocks.Rows[i]["ProgName"].ToString();
                rl["BlockDuration"] = blocks.Rows[i]["BlockDuration"];
                rl["Color"] = "Yellow";
                tbtinklelis.Rows.Add(rl);
                rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = "-1";
                rl["AnonsId"] = "0";
                rl["Color"] = "White";
                tbtinklelis.Rows.Add(rl);
                rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = "-1";
                rl["AnonsId"] = "0";
                rl["Color"] = "White";
                tbtinklelis.Rows.Add(rl);
            }

             if (tbtinklelisInit.Rows.Count == 0)
             {
              
                 List<int>[] ls = new List<int>[auto.Rows.Count];
                 for (int i = 0; i < ls.Length; i++)
                     ls[i] = new List<int>();
                 while(auto.Rows.Count>0){
                  int rowix=GetRandomNumber(0, auto.Rows.Count);
                  int blockid = GetRandomNumber(0, blocks.Rows.Count);
                  string AnonsId = auto.Rows[rowix]["AnonsId"].ToString();
                  while (ls[rowix].Contains(blockid))
                  {
                      blockid = GetRandomNumber(0, blocks.Rows.Count);
                  }
                  for (int i = 0; i < tbtinklelis.Rows.Count; i++)
                  {
                      if (Int32.Parse(tbtinklelis.Rows[i]["BlockPos"].ToString()) == blockid)
                      {
                          //DataRowView rowitem = (DataRowView)item.SelectedItems[0];
                          DataRow rl = tbtinklelis.NewRow();
                          rl["Id"] = "1";
                          string bid = tbtinklelis.Rows[i][3].ToString();
                          rl["BlockPos"] = bid.ToString();
                          rl["BlockId"] = bid.ToString();
                          rl["AnonsId"] = AnonsId;
                          rl["Duration"] = Functionality.getDurationByAnonsId(AnonsId);
                          rl["Name"] = Functionality.getNameByAnonsId(AnonsId);
                          rl["ProgName"] = tbtinklelis.Rows[i]["ProgName"].ToString();
                          rl["ClipName"] = rd.NextDouble().ToString();
                          rl["Color"] = "White";

                          tbtinklelis.Rows.InsertAt(rl, i+1);
                          ls[rowix].Add(blockid);
                          if (Int32.Parse(auto.Rows[rowix]["Amount"].ToString()) > 1) { auto.Rows[rowix]["Amount"] = (Int32.Parse(auto.Rows[rowix]["Amount"].ToString()) - 1).ToString(); }
                          else { auto.Rows.RemoveAt(rowix); }
                          break;
                      }
                  }
                  
                  
                 }
                //    int cnt=GetRandomNumber(1,auto.Rows[rowix]["Amount]
             }
            UpdateDG(tbtinklelis);
            //gridDataTinklelis.ItemsSource = tbtinklelis.AsDataView();

        }

        private void worker_RunWorkerCompleted(object sender,
                                               RunWorkerCompletedEventArgs e)
        {
           
           // splash.Close(new TimeSpan(1000));
            //if (splash.isStarted)

             splash.CloseSplash();
        }

        private void worker_DoWork1(object sender, DoWorkEventArgs e)
        {
            List<object> ls = (List<object>)e.Argument;
            string filename = (string)ls[0];
            DataGrid dataGrid1 = (DataGrid)ls[1];
            DataTable planasTable = (DataTable)ls[2];
            DateTime dt = (DateTime)ls[3];//datePicker2.SelectedDate.Value
            Office.exportPlanasToExcel(filename, dataGrid1, planasTable, dt);
        }

        private void worker_RunWorkerCompleted1(object sender,
                                               RunWorkerCompletedEventArgs e)
        {
            splash.CloseSplash();
            MessageBox.Show("Exportas baigtas!");
        }

        private DataSet SampleData()
        {
            DataSet sampleDataSet = new DataSet();
            sampleDataSet.Locale = CultureInfo.InvariantCulture;
            DataTable sampleDataTable = sampleDataSet.Tables.Add("plan");

            sampleDataTable.Columns.Add("time", typeof(string));
            sampleDataTable.Columns.Add("prog", typeof(string));
            sampleDataTable.Columns.Add("rate", typeof(string));
            sampleDataTable.Columns.Add("blockDuration", typeof(string));
            sampleDataTable.Columns.Add("leftDuration", typeof(string));

            string dayofweek = datePicker2.SelectedDate.Value.DayOfWeek.ToString();
            //DataTable tban = GetDb().getTable("select * from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='" + datePicker2.SelectedDate.Value.ToString() + "'");
            //DataTable tban = GetDb().getTable("select distinct BlockPos,AnonsDate,Name,ClipName,Duration from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='" + datePicker2.SelectedDate.Value.ToString() + "'");
            DataTable tban = GetDb().getTable("select distinct count(BlockPos) as cnt,BlockPos,AnonsDate,Name,ClipName,Duration from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='" + datePicker2.SelectedDate.Value.ToString() + "' group by BlockPos,AnonsDate,Name,ClipName,Duration  order by Name ");
            DataTable tb = GetDb().getTable("select * from BlockAnons where WeekDay like '%" + dayofweek + "%'");
            DataTable tbans = GetDb().getTable("select distinct AnonsDate,Name,ClipName,Duration from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='" + datePicker2.SelectedDate.Value.ToString() + "' group by BlockPos,AnonsDate,Name,ClipName,Duration  order by Name ");
            

            DataRow sampleDataRow;
            sampleDataRow = sampleDataTable.NewRow();
            sampleDataTable.Rows.InsertAt(sampleDataRow, 0);

            for (int i = dataGrid1.Columns.Count - 1; i > 4; i--)
            {
                dataGrid1.Columns.RemoveAt(i);
            }

            for (int i = 0; i < tbans.Rows.Count; i++)
            {
                string colname="an" + i.ToString();
                sampleDataTable.Columns.Add(colname, typeof(string));
                string time = tban.Rows[i]["Duration"].ToString(); //"";//"1:31:00";
                string rv = "0";
                TimeSpan result;
                if (TimeSpan.TryParse(time, out result))
                {
                    rv = result.TotalSeconds.ToString();
                }
                sampleDataTable.Rows[0][i + 5] = rv;
                //sampleDataTable.Rows[1][i+5] = "";

                DataGridTextColumn textColumn = new DataGridTextColumn();
                textColumn.Header = tban.Rows[i]["Name"].ToString();
                textColumn.Binding = new Binding(colname);
                dataGrid1.Columns.Add(textColumn);
            }
            
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                sampleDataRow = sampleDataTable.NewRow();
                if (tb.Rows[i]["AnonsTime"].ToString().Length > 5)
                {
                    sampleDataRow["time"] = tb.Rows[i]["AnonsTime"].ToString().Substring(0, 5);
                }
                else
                {
                    sampleDataRow["time"] = tb.Rows[i]["AnonsTime"].ToString();
                }
                sampleDataRow["prog"] = tb.Rows[i]["ProgName"].ToString();
                sampleDataRow["rate"] = tb.Rows[i]["Rait"].ToString()+"%";
                string time = tb.Rows[i]["BlockDuration"].ToString(); //"";//"1:31:00";
                string rv = "0";
                TimeSpan result;
                if (TimeSpan.TryParse(time, out result))
                {
                    rv = result.TotalSeconds.ToString();
                }
                sampleDataRow["blockDuration"] = rv;
               // sampleDataRow["leftDuration"] = "15";
                sampleDataTable.Rows.Add(sampleDataRow);
            }

            for (int i = 0; i < tban.Rows.Count; i++)
            {
                for (int y = 0; y < tb.Rows.Count; y++)
                {
                    int rowpos=(int)tb.Rows[y]["BlockNr"];
                    int colpos=(int)tban.Rows[i]["BlockPos"];
                    if (rowpos == colpos)
                    {
                        int ix=0;
                        for (int e = 0; e < tbans.Rows.Count; e++)
                        {
                            string name1 = tbans.Rows[e]["Name"].ToString();
                            string name2 = tban.Rows[i]["Name"].ToString();
                            if (name1.Equals(name2))
                            {
                                ix = e;
                            }
                        }
                        //int sum=0;
                        //if (sampleDataTable.Rows[y + 1][i + 5].ToString() == "") { sum = 0; }
                        //else { sum = (int)sampleDataTable.Rows[y + 1][i + 5]; }
                        sampleDataTable.Rows[y+1][ix + 5] =tban.Rows[i]["cnt"].ToString();// sum + 1;
                        
                    }
                }
            }

            for (int y = 0; y < tb.Rows.Count; y++)
            {
                int sum=0;
               for (int i = 0; i < tbans.Rows.Count; i++)
               {
                
                    int cell = 0;
                     if (sampleDataTable.Rows[0][i + 5].ToString() == "") { cell = 0; }
                     else { cell = Int32.Parse(sampleDataTable.Rows[0][i + 5].ToString()); }
                     int cell1 = 0;
                     if (sampleDataTable.Rows[y + 1][i + 5].ToString() == "") { cell1 = 0; }
                     else { cell1 = Int32.Parse(sampleDataTable.Rows[y + 1][i + 5].ToString()); }
                    sum = sum+(cell *cell1);
               }
               int cell2 = 0;
               if (sampleDataTable.Rows[y + 1][3].ToString() == "") { cell2 = 0; }
               else { cell2 = Int32.Parse(sampleDataTable.Rows[y + 1][3].ToString()); }
               sampleDataTable.Rows[y + 1][4] = cell2-sum;
            }
                
            

            
              //  sampleDataRow = sampleDataTable.NewRow();
              //  sampleDataRow["time"] = "07:50";
                //sampleDataRow["prog"] = "Ryto reporteris 2";
               // sampleDataRow["rate"] = "3%";
               // sampleDataRow["blockDuration"] = "172";
               // sampleDataRow["leftDuration"] = "172";
               // sampleDataTable.Rows.Add(sampleDataRow);
           // }


             //  pridedame anonsu stulpelius   

                //int ix = 5;

                

                /*ix++;
                sampleDataTable.Columns.Add("an"+ix, typeof(string));
                sampleDataTable.Rows[0][ix] = "";
                sampleDataTable.Rows[1][ix] = "2";

                textColumn = new DataGridTextColumn();
                textColumn.Header = "Energetikos Aktualijos_1002_rytoj";
                textColumn.Binding = new Binding("an" + ix.ToString());
                dataGrid1.Columns.Add(textColumn);*/

                //pridedame trukmes anonsu pirmoje eiluteje
                /*sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[0] = "";
                sampleDataRow[1] = "";
                sampleDataRow[2] = "";
                sampleDataRow[3] = "";
                sampleDataRow[4] = "";
                sampleDataRow[5] = "32";
                sampleDataRow[6] = "20";
                sampleDataTable.Rows.InsertAt(sampleDataRow, 0);*/

                //pridedama info apacioje
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Faktas";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Kiekis";
                
                for (int i = 0; i < tbans.Rows.Count; i++)
                {
                    int sum = 0;
                    for (int y = 0; y < tb.Rows.Count; y++)
                    {
                        int cell = 0;
                        string cls = sampleDataTable.Rows[y + 1][i + 5].ToString();
                        if (sampleDataTable.Rows[y + 1][i + 5].ToString() == "") { cell = 0; }
                        else { cell = Int32.Parse(sampleDataTable.Rows[y + 1][i+ 5].ToString()); }
                        sum = sum + cell;
                    }
                    sampleDataRow[i+5] = sum;
                }
                //sampleDataRow[5] = "1";
                //sampleDataRow[6] = "0";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Trukme";
                for (int y = 0; y < tbans.Rows.Count; y++)
                {
                    int cell = 0;
                    if (sampleDataTable.Rows[sampleDataTable.Rows.Count - 1][y + 5].ToString() == "") { cell = 0; }
                    else { cell = Int32.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count - 1][y + 5].ToString()); }
                    int cell1 = 0;
                    if (sampleDataTable.Rows[0][y + 5].ToString() == "") { cell1 = 0; }
                    else { cell1 = Int32.Parse(sampleDataTable.Rows[0][y + 5].ToString()); }
                    sampleDataRow[y + 5] = cell * cell1;
                }
               // sampleDataRow[5] = "32";
               // sampleDataRow[6] = "0";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Reitingas";

                for (int i = 0; i < tbans.Rows.Count; i++)
                {
                    double sum = 0;
                    for (int y = 0; y < tb.Rows.Count; y++)
                    {
                        int cell = 0;
                        if (sampleDataTable.Rows[y + 1][i + 5].ToString() == "") { cell = 0; }
                        else { cell = Int32.Parse(sampleDataTable.Rows[y + 1][i + 5].ToString()); }
                        double cell1 = 0;
                        if (sampleDataTable.Rows[y + 1][2].ToString() == "") { cell1 = 0; }
                        else { cell1 = Double.Parse(sampleDataTable.Rows[y + 1][2].ToString().Replace("%","")); }
                        sum = sum + cell*cell1;
                    }
                    sampleDataRow[i + 5] = sum.ToString()+"%";
                }
                //sampleDataRow[5] = "2%";
                //sampleDataRow[6] = "0%";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Planas";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Kiekis";
                //sampleDataRow[5] = "20%";
                //sampleDataRow[6] = "10%";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Trukmė";
                //sampleDataRow[5] = "20%";
                //sampleDataRow[6] = "10%";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Reitingas";
                //sampleDataRow[5] = "20%";
                //sampleDataRow[6] = "10%";
                sampleDataTable.Rows.Add(sampleDataRow);

                sampleDataRow = sampleDataTable.NewRow();
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Skirtumas";
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Kiekis";
                for (int i = 0; i < tbans.Rows.Count; i++)
                {
                    double sum = 0;
                    for (int y = 0; y < tb.Rows.Count; y++)
                    {
                        int cell = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count-5][i + 5].ToString() == "") { cell = 0; }
                        else { cell = Int32.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count-5][i + 5].ToString()); }
                        int cell1 = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count-10][i + 5].ToString() == "") { cell1 = 0; }
                        else { cell1 = Int32.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count-10][i + 5].ToString()); }
                        sum = cell - cell1;
                    }
                    sampleDataRow[i + 5] = sum.ToString();
                }
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Trukmė";
                for (int i = 0; i < tbans.Rows.Count; i++)
                {
                    double sum = 0;
                    for (int y = 0; y < tb.Rows.Count; y++)
                    {
                        int cell = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count - 5][i + 5].ToString() == "") { cell = 0; }
                        else { cell = Int32.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count - 5][i + 5].ToString()); }
                        int cell1 = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count - 10][i + 5].ToString() == "") { cell1 = 0; }
                        else { cell1 = Int32.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count - 10][i + 5].ToString()); }
                        sum = cell - cell1;
                    }
                    sampleDataRow[i + 5] = sum.ToString();
                }
                sampleDataTable.Rows.Add(sampleDataRow);
                sampleDataRow = sampleDataTable.NewRow();
                sampleDataRow[1] = "Reitingas";
                for (int i = 0; i < tbans.Rows.Count; i++)
                {
                    double sum = 0;
                    for (int y = 0; y < tb.Rows.Count; y++)
                    {
                        double cell = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count - 5][i + 5].ToString() == "") { cell = 0; }
                        else { cell = double.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count - 5][i + 5].ToString().Replace("%", "")); }
                        double cell1 = 0;
                        if (sampleDataTable.Rows[sampleDataTable.Rows.Count - 10][i + 5].ToString() == "") { cell1 = 0; }
                        else { cell1 = double.Parse(sampleDataTable.Rows[sampleDataTable.Rows.Count - 10][i + 5].ToString().Replace("%","")); }
                        sum = cell - cell1;
                    }
                    sampleDataRow[i + 5] = sum.ToString()+"%";
                }
                sampleDataTable.Rows.Add(sampleDataRow);

            return sampleDataSet;
        }

        
    

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Calendar_AddAppointment(object sender, RoutedEventArgs e)
        {

        }

        private void Ribbon_SelectedTabChanged(object sender, SelectionChangedEventArgs e)
        {
           // int ix = ((RibbonTabControl)e.Source).SelectedIndex;
            if (TabAnonsai.IsSelected)
            {
                gridTinklelis.Visibility = Visibility.Hidden;
                gridControl1.Visibility = Visibility.Visible;
                gridControl2.Visibility = Visibility.Hidden;
                gridPlanas.Visibility = Visibility.Hidden;
                gridBlocks.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Hidden;
            }
            if (TabKlipai.IsSelected)
            {
                gridTinklelis.Visibility = Visibility.Hidden;
                gridControl1.Visibility = Visibility.Hidden;
                gridControl2.Visibility = Visibility.Visible;
                gridPlanas.Visibility = Visibility.Hidden;
                gridBlocks.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Hidden;
            }
            if (TabBlokai.IsSelected)
            {
                gridBlocks.Visibility = Visibility.Visible;
                gridTinklelis.Visibility = Visibility.Hidden;
                gridControl1.Visibility = Visibility.Hidden;
                gridControl2.Visibility = Visibility.Hidden;
                gridPlanas.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Hidden;
            }
            if (TabTinklelis.IsSelected)
            {
                gridTinklelis.Visibility = Visibility.Visible;
                gridControl1.Visibility = Visibility.Hidden;
                gridControl2.Visibility = Visibility.Hidden;
                gridPlanas.Visibility = Visibility.Hidden;
                gridBlocks.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Hidden;
            }
            if (TabPlanas.IsSelected)
            {
                gridTinklelis.Visibility = Visibility.Hidden;
                gridControl1.Visibility = Visibility.Hidden;
                gridControl2.Visibility = Visibility.Hidden;
                gridPlanas.Visibility = Visibility.Visible;
                gridBlocks.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Hidden;
            }
            if (TabAutoPlanas.IsSelected)
            {
                gridTinklelis.Visibility = Visibility.Hidden;
                gridControl1.Visibility = Visibility.Hidden;
                gridControl2.Visibility = Visibility.Hidden;
                gridPlanas.Visibility = Visibility.Hidden;
                gridBlocks.Visibility = Visibility.Hidden;
                gridAutoPlan.Visibility = Visibility.Visible;
            }

            /*   bool issel=TabAnonsai.IsSelected;
            if (ix>=0)
            {
                switch (ix)
                {
                    case 0:
                        //gridDataTinklelis.Visibility = Visibility.Hidden;
                        gridTinklelis.Visibility = Visibility.Hidden;
                        gridControl1.Visibility = Visibility.Visible;
                        gridControl2.Visibility = Visibility.Hidden;
                        gridPlanas.Visibility = Visibility.Hidden;
                        gridBlocks.Visibility = Visibility.Hidden;
                        break;
                    case 1:
                       // gridDataTinklelis.Visibility = Visibility.Hidden;
                        gridTinklelis.Visibility = Visibility.Hidden;
                        gridControl1.Visibility = Visibility.Hidden;
                        gridControl2.Visibility = Visibility.Visible;
                        gridPlanas.Visibility = Visibility.Hidden;
                        gridBlocks.Visibility = Visibility.Hidden;
                        break;
                    case 2:
                        //gridDataTinklelis.Visibility = Visibility.Visible;
                      //  if (datePicker1.Text.Contains("")){
                     //       datePicker1.DisplayDate = DateTime.Now;
                     //       datePicker1.Text = DateTime.Now.ToShortDateString();
                      //  }
                        gridBlocks.Visibility = Visibility.Visible;
                        gridTinklelis.Visibility = Visibility.Hidden;
                        gridControl1.Visibility = Visibility.Hidden;
                        gridControl2.Visibility = Visibility.Hidden;
                        gridPlanas.Visibility = Visibility.Hidden;
                        break;
                    case 3:
                       // gridDataTinklelis.Visibility = Visibility.Hidden;
                        gridTinklelis.Visibility = Visibility.Visible;
                        gridControl1.Visibility = Visibility.Hidden;
                        gridControl2.Visibility = Visibility.Hidden;
                        gridPlanas.Visibility = Visibility.Hidden;
                        gridBlocks.Visibility = Visibility.Hidden;
                        break;
                    case 4:
                        // gridDataTinklelis.Visibility = Visibility.Hidden;
                        gridTinklelis.Visibility = Visibility.Hidden;
                        gridControl1.Visibility = Visibility.Hidden;
                        gridControl2.Visibility = Visibility.Hidden;
                        gridPlanas.Visibility = Visibility.Visible;
                        gridBlocks.Visibility = Visibility.Hidden;
                        break;
                }
            }*/
        }


        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void anNewButton_Click(object sender, RoutedEventArgs e)
        {
            AnnouncInsert ai = new AnnouncInsert();
            if (ai.ShowDialog() == true)
            {
                Functionality.AddAnons(ai.textBox1.Text, ai.AnonsId);
                Functionality.serachAnons(gridControl1, serachAnWord);
            }
        }

        private void planRefreshButton_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void clipNewButton_Click(object sender, RoutedEventArgs e)
        {
            ClipInsert clpi = new ClipInsert();
            if (clpi.ShowDialog() == true)
            {
                Functionality.AddClip(clpi.textBox1.Text, clpi.textBox2.Text);
                Functionality.serachClips(gridControl2, clpi.textBox1.Text);
            }
        }

        private void clipEditButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = gridControl2.View.GetSelectedRowHandles()[0];
            object id = gridControl2.GetCellValue(selectedRowhandle, "id");
            object name = gridControl2.GetCellValue(selectedRowhandle, "ClipName");
            object duration = gridControl2.GetCellValue(selectedRowhandle, "Duration");
            ClipInsert clpi = new ClipInsert();
            clpi.textBox1.Text=name.ToString();
            clpi.textBox2.Text = duration.ToString();
            if (clpi.ShowDialog() == true)
            {
                Functionality.EditClip(id.ToString(),clpi.textBox1.Text, clpi.textBox2.Text);
                Functionality.serachClips(gridControl2, clpi.textBox1.Text);
            }
        }

        private void clipDerleteButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = gridControl2.View.GetSelectedRowHandles()[0];
            object id = gridControl2.GetCellValue(selectedRowhandle, "id");
            string sMessageBoxText = "Ar tikrai norite ištrinti šį įrašą?";
            string sCaption = "Patvirtinimas";

            MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
            MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

            MessageBoxResult rsltMessageBox = System.Windows.MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);
            if (rsltMessageBox == MessageBoxResult.Yes)
            {
                Functionality.deleteClip(id.ToString());
                Functionality.serachClips(gridControl2, serachWord);
            }
        }

        private void clipSearchButton_Click(object sender, RoutedEventArgs e)
        {
            SearchWindow sw = new SearchWindow();
            if (sw.ShowDialog() == true)
            {
                serachWord = sw.textBox1.Text;
                Functionality.serachClips(gridControl2, serachWord);
            }
        }

        private void anSearchButton_Click(object sender, RoutedEventArgs e)
        {
            SearchWindow sw = new SearchWindow();
            if (sw.ShowDialog() == true)
            {
                serachAnWord = sw.textBox1.Text;
                Functionality.serachAnons(gridControl1, serachAnWord);
            }
        }

        private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
           /* DataBase db = new DataBase("192.168.100.100\\SQLEXPRESS", "sa", "tornado", "PASystem");
            DataTable blocks = db.getTable("select * from Blocks order by Block_Name");
            
            DataTable tbtinklelisTmp = db.getTable("select * from AnonsData where AnonsDate='" + datePicker1.Text + "'");
            List<DataTable> arguments = new List<DataTable>();
            arguments.Add(blocks);
            arguments.Add(tbtinklelis);
            arguments.Add(tbtinklelisTmp); */
            splash.ShowSplash();
            //splash.Show(false, true);
            tbtinklelis = GetDb().getTable("select * from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='1900-01-01'");
            if (!tbtinklelis.Columns.Contains("Color"))
                tbtinklelis.Columns.Add("Color", typeof(string));
            gridDataTinklelis.ItemsSource = tbtinklelis.AsDataView();
            if (!worker.IsBusy)
                worker.RunWorkerAsync(datePicker1.Text);
           /* DataBase db = new DataBase("192.168.100.100\\SQLEXPRESS", "sa", "tornado", "PASystem");
            DataTable blocks = db.getTable("select * from Blocks order by Block_Name");
            tbtinklelis = db.getTable("select * from AnonsData ad left join Anonsai an on ad.AnonsId=an.id left join AnonsaiClips anc on an.ClipId=anc.id where AnonsDate='1900-01-01'");
            if (!tbtinklelis.Columns.Contains("Color"))
                tbtinklelis.Columns.Add("Color", typeof(string));
             gridDataTinklelis.ItemsSource = tbtinklelis.AsDataView();
            for (int i = 0; i < blocks.Rows.Count; i++)
            {
                DataRow rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                string bpos = blocks.Rows[i][1].ToString().Replace("Blokas", "");
                rl["BlockPos"] = Int32.Parse(bpos);
                string bid = blocks.Rows[i][1].ToString().Replace("Blokas", "");
                rl["BlockId"] = Int32.Parse(bid);
                rl["AnonsId"] = "1";
                rl["Color"] = "Red";
                tbtinklelis.Rows.Add(rl);
                DataTable tbtinklelisTmp = GetDb().getTable("select * from AnonsData where AnonsDate='" + datePicker1.Text + "' and BlockId=" + bid);
                for (int y = 0; y < tbtinklelisTmp.Rows.Count; y++)
                {
                    rl = tbtinklelis.NewRow();
                    rl["Id"] = "1";
                    rl["BlockPos"] = tbtinklelisTmp.Rows[y]["BlockPos"].ToString();
                    rl["BlockId"] = tbtinklelisTmp.Rows[y]["BlockId"].ToString();
                    rl["AnonsId"] = tbtinklelisTmp.Rows[y]["AnonsId"].ToString();
                    rl["Color"] = "Grey";
                    tbtinklelis.Rows.Add(rl);
                }
                rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = "-1";
                rl["AnonsId"] = "1";
                rl["Color"] = "Green";
                tbtinklelis.Rows.Add(rl);
                rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = "-1";
                rl["AnonsId"] = "0";
                rl["Color"] = "White";
                tbtinklelis.Rows.Add(rl);
            }*/
             //gridControlTinklelis.DataSource = tbtinklelis;
            // loadTinklelis(gridControlTinklelis, tbtinklelis);
        }

        public void loadTinklelis(DevExpress.Xpf.Grid.GridControl dg, System.Data.DataTable dt)
        {
            //DataRowView rowitem = (DataRowView)dg.rows
            //((DevExpress.Xpf.Grid.TableView)dg.View).SelectAll();

            //(dg.View as DevExpress.Xpf.Grid.View.XtraGrid.Views.Grid.GridView).AddNewRow();
            /*var selectedRowHandles = ((DevExpress.Xpf.Grid.TableView)dg.View).GetSelectedRowHandles().AsEnumerable();

            foreach (var item in selectedRowHandles)
            {
                object rw=dg.GetRow(item);
            }*/
        }

        private void gridTinklelis_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            //load
        }

        private void datePicker2_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            planasTable=SampleData().Tables["plan"];
            dataGrid1.ItemsSource = planasTable.AsDataView();
        }

        private void gridTinklelis_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

     /*   private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

            var item = gridControlTinklelis;
            TinklelisAdd ta = new TinklelisAdd();
             if (ta.ShowDialog() == true)
            {
                DataRow rl = tbtinklelis.NewRow();
                rl["Id"] = "1";
                rl["BlockPos"] = "2";
                rl["AnonsId"] = ta.AnonsId;

                rl["ClipName"] = rd.NextDouble().ToString();
                rl["Duration"] = "00:00:10";
                rl["Color"] = "Red";
                
                if (item.View.SelectedRows.Count > 0)
                {
                    DataRowView rowitem = (DataRowView)item.View.SelectedRows[0];
                    tbtinklelis.Rows.InsertAt(rl, tbtinklelis.Rows.IndexOf(rowitem.Row));
                }
                else
                {
                    tbtinklelis.Rows.Add(rl);
                }
            }
           
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            var item = gridControlTinklelis;
            DataRowView toDeleteFromBindedList = (DataRowView)item.View.SelectedRows[0];
            tbtinklelis.Rows.Remove(toDeleteFromBindedList.Row);
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            var item = gridControlTinklelis;
            if (item.View.SelectedRows.Count > 0)
            {
                DataRowView rowitem = (DataRowView)item.View.SelectedRows[0];
                int ix = tbtinklelis.Rows.IndexOf(rowitem.Row);
                TinklelisAdd ta = new TinklelisAdd();
                if (ta.ShowDialog() == true)
                {
                    DataRow rl = tbtinklelis.NewRow();
                    rl["Id"] = "1";
                    rl["BlockPos"] = "2";
                    rl["Name"] = "Ryto reporteris1 1";

                    rl["ClipName"] = rd.NextDouble().ToString();
                    rl["Duration"] = "00:00:10";
                    rl["Color"] = "Green";

                    
                    tbtinklelis.Rows.RemoveAt(ix);
                    tbtinklelis.Rows.InsertAt(rl, ix);

                }
            }
        }*/

        private void MenuItem_Click_tg(object sender, RoutedEventArgs e)
        {
            if (gridDataTinklelis!=null)
                if (gridDataTinklelis.SelectedItems.Count > 0)
                {
                    DataGrid item = gridDataTinklelis;
                    string bpos = tbtinklelis.Rows[item.SelectedIndex - 1][4].ToString();
                    string bid = tbtinklelis.Rows[item.SelectedIndex - 1][3].ToString();
                    string starttime = "00:00:00";//tbtinklelis.Rows[item.SelectedIndex - 1][3].ToString();
                    if (!bpos.Equals("-1"))
                    {
                        TinklelisAdd ta = new TinklelisAdd();
                        if (ta.ShowDialog() == true)
                        {
                            DataRow rl = tbtinklelis.NewRow();
                            rl["Id"] = "1";
                            rl["BlockId"] = bid;
                            rl["BlockPos"] = bpos;
                            rl["StartTime"] = starttime;
                            rl["AnonsId"] = ta.AnonsId;
                            rl["Duration"] = Functionality.getDurationByAnonsId(ta.AnonsId.ToString());
                            rl["Name"] = Functionality.getNameByAnonsId(ta.AnonsId.ToString());
                            rl["ProgName"] = tbtinklelis.Rows[item.SelectedIndex - 1]["ProgName"].ToString();
                            // rl["ClipName"] = rd.NextDouble().ToString();
                            //rl["Duration"] = "00:00:10";
                            rl["Color"] = "Grey";

                            if (item.SelectedItems.Count > 0)
                            {
                                // AnnounceRecord rowitem = (AnnounceRecord)item.SelectedItems[0];
                                tbtinklelis.Rows.InsertAt(rl, item.SelectedIndex);
                            }
                            else
                            {
                                tbtinklelis.Rows.Add(rl);
                            }
                            recalcStartTime(tbtinklelis);
                        }

                    }
                }

        }

        private void MenuItem_Click_1_tg(object sender, RoutedEventArgs e)
        {
            if (gridDataTinklelis!=null)
                if (gridDataTinklelis.SelectedItems.Count > 0)
                {
                    DataGrid item = gridDataTinklelis;// (DevExpress.Xpf.Grid.GridControl)tinklelis_menu.PlacementTarget;
                    DataRowView toDeleteFromBindedList = (DataRowView)item.SelectedItems[0];
                    tbtinklelis.Rows.RemoveAt(item.SelectedIndex);//toDeleteFromBindedList.Row);
                    recalcStartTime(tbtinklelis);
                }
        }

        private void MenuItem_Click_2_tg(object sender, RoutedEventArgs e)
        {
            if (gridDataTinklelis!=null)
                if (gridDataTinklelis.SelectedItems.Count > 0)
                {
                    DataGrid item = gridDataTinklelis;// (DevExpress.Xpf.Grid.GridControl)tinklelis_menu.PlacementTarget;
                    if (item.SelectedItems.Count > 0)
                    {
                        //DataRowView rowitem = (DataRowView)item.SelectedItems[0];
                        int ix = item.SelectedIndex;// tbtinklelis.Rows.IndexOf(rowitem.Row);
                        TinklelisAdd ta = new TinklelisAdd();
                        if (ta.ShowDialog() == true)
                        {
                            DataRow rl = tbtinklelis.NewRow();
                            rl["Id"] = "1";
                            string bid = tbtinklelis.Rows[item.SelectedIndex - 1][3].ToString();
                            rl["BlockPos"] = bid.ToString();
                            rl["BlockId"] = bid.ToString();
                            rl["AnonsId"] = ta.AnonsId;
                            rl["Duration"] = Functionality.getDurationByAnonsId(ta.AnonsId.ToString());
                            rl["Name"] = Functionality.getNameByAnonsId(ta.AnonsId.ToString());
                            rl["ProgName"] = tbtinklelis.Rows[item.SelectedIndex - 1]["ProgName"].ToString();
                            rl["ClipName"] = rd.NextDouble().ToString();
                           // rl["Duration"] = "00:00:10";
                            rl["Color"] = "White";


                            tbtinklelis.Rows.RemoveAt(ix);
                            tbtinklelis.Rows.InsertAt(rl, ix);

                        }
                    }
                    recalcStartTime(tbtinklelis);
                }
        }


        private void tinklelisNewButton_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_Click_tg(sender, e);
        }

        private void tinklelisEditButton_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_Click_2_tg(sender, e);
        }

        private void tinklelisDerleteButton_Click(object sender, RoutedEventArgs e)
        {
            MenuItem_Click_1_tg(sender, e);
        }

        private void planExportButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void tinklelisExportButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Document"; // Default file name
            dlg.DefaultExt = ".xls"; // Default file extension
            dlg.Filter = "Excel documentai (.xls)|*.xls"; // Filter files by extension

            Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string filename = dlg.FileName;
                try
                {
                    Office.exportTinklelisToExcel(filename, tbtinklelis, datePicker1.SelectedDate.Value);
                    MessageBox.Show("Exportas baigtas!");
                }
                catch (Exception ex) { MessageBox.Show("Įvyko klaida eksportuojant į Excel!"); }
            }
        }

        private void tinklelisSaveButton_Click(object sender, RoutedEventArgs e)
        {
            GetDb().sqlExecute("delete from AnonsData where AnonsDate='" + datePicker1.Text + "'");
            for (int i = 0; i < tbtinklelis.Rows.Count; i++)
            {
                if ((!tbtinklelis.Rows[i]["BlockPos"].ToString().Equals("-1")) && (!tbtinklelis.Rows[i]["AnonsId"].ToString().Equals("1")))
                {
                    string sql = "insert into AnonsData (AnonsId,AnonsDate,BlockId,BlockPos)values(" + tbtinklelis.Rows[i]["AnonsId"].ToString() + ",'" + datePicker1.Text + "'," + tbtinklelis.Rows[i]["BlockId"].ToString() + "," + tbtinklelis.Rows[i]["BlockPos"].ToString() + ")";
                    GetDb().sqlExecute(sql);
                }
            }
            //
        }

        private void blockEditButton_Click(object sender, RoutedEventArgs e)
        {
            if (blocksTabs.SelectedIndex == 0)
            {
                Functionality.saveBlocks(blockGrid1, "Monday");
            }
            else if (blocksTabs.SelectedIndex == 1)
            {
                Functionality.saveBlocks(blockGrid2, "Tuesday");
            }
            else if (blocksTabs.SelectedIndex == 2)
            {
                Functionality.saveBlocks(blockGrid3, "Wednesday");
            }
            else if (blocksTabs.SelectedIndex == 3)
            {
                Functionality.saveBlocks(blockGrid4, "Thursday");
            }
            else if (blocksTabs.SelectedIndex == 4)
            {
                Functionality.saveBlocks(blockGrid5, "Friday");
            }
            else if (blocksTabs.SelectedIndex == 5)
            {
                Functionality.saveBlocks(blockGrid6, "Saturday");
            }
            else if (blocksTabs.SelectedIndex == 6)
            {
                Functionality.saveBlocks(blockGrid7, "Sunday");
            }
            else if (blocksTabs.SelectedIndex == 7)
            {
                Functionality.saveBlocks(dateBlock.blockGrid8, dateBlock.datePickerBlock.SelectedDate.Value.ToShortDateString());
            }
        }

        private void planExportButton_Click_1(object sender, RoutedEventArgs e)
        {
            if ((planasTable) != null)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "Document"; // Default file name
                dlg.DefaultExt = ".xls"; // Default file extension
                dlg.Filter = "Excel documentai (.xls)|*.xls"; // Filter files by extension

                Nullable<bool> result = dlg.ShowDialog();
                if (result == true)
                {
                    string filename = dlg.FileName;
                    try
                    {
                       /* Office.mw = this;
                        List<object> ls = new List<object>();
                        ls.Add(filename);
                        ls.Add(dataGrid1);
                        ls.Add(planasTable);
                        ls.Add(datePicker2.SelectedDate.Value);
                        splash.ShowSplash();
                        if (!worker1.IsBusy)
                            worker1.RunWorkerAsync(ls);*/
                        Office.exportPlanasToExcel(filename, dataGrid1, planasTable, datePicker2.SelectedDate.Value);
                        MessageBox.Show("Exportas baigtas!");
                    }
                    catch (Exception ex) { MessageBox.Show("Įvyko klaida eksportuojant į Excel!"); }
                }
            }
        }

        private void MenuItem_Click_3_tg(object sender, RoutedEventArgs e)
        {
            if (gridDataTinklelis != null)
                if (gridDataTinklelis.SelectedItems.Count > 0)
                {
                    DataGrid item = gridDataTinklelis;// (DevExpress.Xpf.Grid.GridControl)tinklelis_menu.PlacementTarget;
                    if (item.SelectedItems.Count > 0)
                    {
                        //DataRowView rowitem = (DataRowView)item.SelectedItems[0];
                        int ix = item.SelectedIndex;// tbtinklelis.Rows.IndexOf(rowitem.Row);
                        copyAnonsId = tbtinklelis.Rows[item.SelectedIndex]["AnonsId"].ToString();
                    }
                }
        }

        private void MenuItem_Click_4_tg(object sender, RoutedEventArgs e)
        {
           if  (!copyAnonsId.Equals("-1"))
            if (gridDataTinklelis != null)
                if (gridDataTinklelis.SelectedItems.Count > 0)
                {
                    DataGrid item = gridDataTinklelis;// (DevExpress.Xpf.Grid.GridControl)tinklelis_menu.PlacementTarget;
                    if (item.SelectedItems.Count > 0)
                    {
                        //DataRowView rowitem = (DataRowView)item.SelectedItems[0];
                        int ix = item.SelectedIndex;// tbtinklelis.Rows.IndexOf(rowitem.Row);
                         DataRow rl = tbtinklelis.NewRow();
                            rl["Id"] = "1";
                            string bid = tbtinklelis.Rows[item.SelectedIndex - 1][3].ToString();
                            rl["BlockPos"] = bid.ToString();
                            rl["BlockId"] = bid.ToString();
                            rl["AnonsId"] = copyAnonsId;
                            rl["Duration"] = Functionality.getDurationByAnonsId(copyAnonsId.ToString());
                            rl["Name"] = Functionality.getNameByAnonsId(copyAnonsId.ToString());
                            rl["ProgName"] = tbtinklelis.Rows[item.SelectedIndex - 1]["ProgName"].ToString();
                            rl["ClipName"] = rd.NextDouble().ToString();
                            // rl["Duration"] = "00:00:10";
                            rl["Color"] = "White";

                            tbtinklelis.Rows.InsertAt(rl, ix);
                    }
                    recalcStartTime(tbtinklelis);
                }
        }

        private void MenuItem_Click_5_tg(object sender, RoutedEventArgs e)
        {
                if (gridDataTinklelis != null)
                    if (gridDataTinklelis.SelectedItems.Count > 0)
                    {
                        DataGrid item = gridDataTinklelis;// (DevExpress.Xpf.Grid.GridControl)tinklelis_menu.PlacementTarget;
                        if (item.SelectedItems.Count > 0)
                        {
                            int ix = item.SelectedIndex;
                            copyAnonsId = tbtinklelis.Rows[item.SelectedIndex ]["AnonsId"].ToString();
                            tbtinklelis.Rows.RemoveAt(ix);
                        }
                        recalcStartTime(tbtinklelis);
                    }
        }

        private void gridDataTinklelis_KeyUp(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.V || e.Key == Key.X || e.Key == Key.C || e.Key == Key.S) && Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                if (e.Key == Key.V) MenuItem_Click_4_tg(sender, null);
                if (e.Key == Key.X) MenuItem_Click_5_tg(sender, null);
                if (e.Key == Key.C) MenuItem_Click_3_tg(sender, null);
                if (e.Key == Key.S) tinklelisSaveButton_Click(sender, null);
            }
                return;
        }

        private void gridDataTinklelis_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            int cnt = 0;
            for (int y = 0; y < MainRibbon.Tabs.Count; y++)
            {
                if (MainRibbon.Tabs[y].IsEnabled)
                {
                    MainRibbon.Tabs[y].IsSelected = true;
                    cnt++;
                    break;
                }
            }
            if (cnt==0){
                this.Close();
            }
        }

        private void insertRowButton_Click(object sender, RoutedEventArgs e)
        {
            DevExpress.Xpf.Grid.GridControl dg=new DevExpress.Xpf.Grid.GridControl();
            if (blocksTabs.SelectedIndex == 0)
            {
                dg=blockGrid1;
            }
            else if (blocksTabs.SelectedIndex == 1)
            {
                dg = blockGrid2;
            }
            else if (blocksTabs.SelectedIndex == 2)
            {
                dg = blockGrid3;
            }
            else if (blocksTabs.SelectedIndex == 3)
            {
                dg = blockGrid4;
            }
            else if (blocksTabs.SelectedIndex == 4)
            {
                dg = blockGrid5;
            }
            else if (blocksTabs.SelectedIndex == 5)
            {
                dg = blockGrid6;
            }
            else if (blocksTabs.SelectedIndex == 6)
            {
                dg = blockGrid7;
            }
            else if (blocksTabs.SelectedIndex == 7)
            {
                dg = dateBlock.blockGrid8;
            }
            int selectedRowhandle = dg.View.GetSelectedRowHandles()[0];
            object id = dg.GetCellValue(selectedRowhandle, "id");
            DataTable tb = (DataTable)dg.DataSource;
            DataRow rl = tb.NewRow();
            tb.Rows.InsertAt(rl, selectedRowhandle);
            dg.DataSource = tb;
        }

        private void blockDerleteButton_Click(object sender, RoutedEventArgs e)
        {
            DevExpress.Xpf.Grid.GridControl dg = new DevExpress.Xpf.Grid.GridControl();
            if (blocksTabs.SelectedIndex == 0)
            {
                dg = blockGrid1;
            }
            else if (blocksTabs.SelectedIndex == 1)
            {
                dg = blockGrid2;
            }
            else if (blocksTabs.SelectedIndex == 2)
            {
                dg = blockGrid3;
            }
            else if (blocksTabs.SelectedIndex == 3)
            {
                dg = blockGrid4;
            }
            else if (blocksTabs.SelectedIndex == 4)
            {
                dg = blockGrid5;
            }
            else if (blocksTabs.SelectedIndex == 5)
            {
                dg = blockGrid6;
            }
            else if (blocksTabs.SelectedIndex == 6)
            {
                dg = blockGrid7;
            }
            else if (blocksTabs.SelectedIndex == 7)
            {
                dg = dateBlock.blockGrid8;
            }
            int selectedRowhandle = dg.View.GetSelectedRowHandles()[0];
            DataTable tb = (DataTable)dg.DataSource;
            DataRow rl = tb.NewRow();
            tb.Rows.RemoveAt( selectedRowhandle);
            dg.DataSource = tb;
        }

        private void blocksKeyup(object sender, KeyEventArgs e)
        {
           // if (e.Key == Key.Delete) blockDerleteButton_Click(sender, null);
        }

        private void anEditButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = gridControl1.View.GetSelectedRowHandles()[0];
            object id = gridControl1.GetCellValue(selectedRowhandle, "id");
            object name = gridControl1.GetCellValue(selectedRowhandle, "Name");
            object clipname = gridControl1.GetCellValue(selectedRowhandle, "ClipName");
            AnnouncInsert anI = new AnnouncInsert();
            anI.textBox1.Text = name.ToString();
            DataTable tb = Functionality.dbc.getTable("select id from AnonsaiClips where ClipName='" + clipname + "'");
            string clipid = "0";
            if (tb.Rows.Count > 0)
            {
                clipid = tb.Rows[0][0].ToString();
            }
            anI.AnonsId = clipid;
            //anI.AnonsNameTextBox.Text = clipname.ToString();
            if (anI.ShowDialog() == true)
            {
                Functionality.EditAnons(id.ToString(), anI.textBox1.Text, anI.AnonsId);
                Functionality.serachAnons(gridControl2, anI.textBox1.Text);
            }
        }

        private void anDeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = gridControl1.View.GetSelectedRowHandles()[0];
            object id = gridControl1.GetCellValue(selectedRowhandle, "id");
            string sMessageBoxText = "Ar tikrai norite ištrinti šį įrašą?";
            string sCaption = "Patvirtinimas";

            MessageBoxButton btnMessageBox = MessageBoxButton.YesNo;
            MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

            MessageBoxResult rsltMessageBox = System.Windows.MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);
            if (rsltMessageBox == MessageBoxResult.Yes)
            {
                Functionality.deleteAnons(id.ToString());
                Functionality.serachAnons(gridControl1, serachWord);
            }
        }

        private void datePickerAutoPlan_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            Functionality.getAutoPlan(dataGridAutoPlan, datePickerAutoPlan.SelectedDate.Value.ToShortDateString());
        }

        private void autoNewButton_Click(object sender, RoutedEventArgs e)
        {
             TinklelisAdd ta = new TinklelisAdd();
             if (ta.ShowDialog() == true)
             {
                 int selectedRowhandle = dataGridAutoPlan.SelectedIndex;
                 if (selectedRowhandle == -1) selectedRowhandle = 0;
                 DataTable tb = ((DataView)dataGridAutoPlan.ItemsSource).ToTable();
                 DataRow rl = tb.NewRow();
                 rl["AnonsId"] = ta.AnonsId;
                 tb.Rows.InsertAt(rl, selectedRowhandle);
                 dataGridAutoPlan.ItemsSource = tb.AsDataView();
             }
        }

        private void autoEditButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = dataGridAutoPlan.SelectedIndex;
            if (selectedRowhandle == -1) selectedRowhandle = 0;
            DataTable tb = ((DataView)dataGridAutoPlan.ItemsSource).ToTable();

            TinklelisAdd ta = new TinklelisAdd();
            ta.AnonsId = tb.Rows[selectedRowhandle]["AnonsId"].ToString();
            if (ta.ShowDialog() == true)
            {
                tb.Rows[selectedRowhandle]["AnonsId"] = ta.AnonsId;
                dataGridAutoPlan.ItemsSource = tb.AsDataView();
            }
        }

        private void autoDerleteButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedRowhandle = dataGridAutoPlan.SelectedIndex;
            if (selectedRowhandle == -1) selectedRowhandle = 0;
            DataTable tb = ((DataView)dataGridAutoPlan.ItemsSource).ToTable();
            tb.Rows.RemoveAt(selectedRowhandle);
            dataGridAutoPlan.ItemsSource = tb.AsDataView();
        }

        private void autoSaveButton_Click(object sender, RoutedEventArgs e)
        {
            Functionality.saveAutoPlanToDb(((DataView)dataGridAutoPlan.ItemsSource).ToTable(), datePickerAutoPlan.SelectedDate.Value.ToShortDateString());
        }

        
    }

    public class Plan
    {
        #region Properties
        public string time { get; set; }
        public string prog { get; set; }
        public string rate { get; set; }
        public string blockDuration { get; set; }
        public string leftDuration { get; set; }
        public string an1 { get; set; }
        public string an2 { get; set; }

#endregion
    }

    public class Anounc
    {
        #region Properties
        public int duration { get; set; }
        public string name { get; set; }
        public int calcAmount { get; set; }
        public int calcDuration { get; set; }
        public string rate { get; set; }
        public string planAmount { get; set; }

        #endregion
    }

    
    public class AnnounceRecord
    {
        public AnnounceRecord(int id, string Name, int ClipId, string ClipName, string Duration)
        {
            this._name = Name;
            this._duration = Duration;
            this._clipid = ClipId;
            this._clipname = ClipName;
            this._id = id;
        }

        #region Private Members
        private string _name;
        private string _clipname;
        private string _duration;
        private int _clipid;
        private int _id;
        #endregion

        #region Properties

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string Duration
        {
            get { return _duration; }
            set { _duration = value; }
        }

        public string ClipName
        {
            get { return _clipname; }
            set { _clipname = value; }
        }

        public int Clip
        {
            get { return _clipid; }
            set { _clipid = value; }
        }

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }

 
        #endregion
    }


    

    


  public class Splasher
  {
    private static Window mSplash;
    public bool isStarted;

    public static Window Splash
    {
      get
      {
        return mSplash;
      }
      set
      {
        mSplash = value;
      }
    }


    public void ShowSplash()
    {
      if (mSplash != null)
      {
        mSplash.Dispatcher.BeginInvoke(new Action(() =>
        {
          mSplash.Close();
        }));
      }

      System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
      {
          Splash = new AnonsaiWPF.SplashScreen();
          Splash.ShowDialog();
      }));
      thread.SetApartmentState(System.Threading.ApartmentState.STA);
      thread.Start();
      isStarted = true; 
    }
    public void CloseSplash()
    {
      if (mSplash != null)
      {
        mSplash.Dispatcher.BeginInvoke(new Action(() =>
          {
            mSplash.Close();
            isStarted = false; 
          }));
        if (mSplash is IDisposable)
        {
            (mSplash as IDisposable).Dispose();
            isStarted = false; 
        }
      }
     
    }
  }
}
